package Stackdemo;

import java.util.Stack;
//括号匹配
public class IsValid {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for(int i = 0;i<s.length();i++){
            char ch = s.charAt(i);
            if(ch == '('||ch == '['||ch == '{'){
                //左括号入栈
                stack.push(ch);
            }else{
                //右括号多
                if(stack.empty()){
                    return false;
                }
                //右括号取出栈顶元素匹配
                char c = stack.peek();
                //括号不匹配
                if((c == '('&&ch==')')||(c == '['&&ch==']')||(c == '{'&&ch=='}')) {
                    stack.pop();
                }else{
                    return false;
                }
            }
        }
        //遍历结束栈中还有元素说明左括号多
        if(!stack.empty()){
            return false;
        }
        return true;
    }
}
